﻿document.write("<script language='javascript' src='/resources/js/views/commonFunction.js'></script>");
document.write("<script language='javascript' src='/resources/js/views/defineTable.js'></script>");

var depart ="/report/query/indicatorType.do"; //获取领域下所有指标接口路径
var iHeight = document.documentElement.clientHeight-200;//判断表格自适应高度
var curPage = 1;
var pageSize = 30;
var seriesData=[];
var arr=[];
var open = false;
var selectAll = false;

function loadYear(){
	$('#year').combobox({  
		onLoadSuccess: function () {
		},
		onSelect: function(index, row){
            queryList();
        }
	});
}

function query(curPage, pageSize,isshow,isTrue){
	
	    curPage = parseInt(curPage);
	    pageSize = parseInt(pageSize);
	    
	    seriesData=[];
	    dataData=[];
	    arr = [];   
  
	    var indicatorType = $("#indicatorType").combobox("getValue"); //领域
	    var year = $("#year").combobox("getValue");//年份
	    var iname=$('#depart_targetSelect').val();//模糊搜索
	    var ck = {
				title : '',
				field : 'ck',
				checkbox : true,
				width : 90
			};
		var reportShowColumns = [];
		reportShowColumns.push(ck);
		reportShowColumns.push(defineTableReportAllColumns["iname"]);//指标名称
		reportShowColumns.push(defineTableReportAllColumns["code"]);//指标名称
		reportShowColumns.push(defineTableReportAllColumns["unit"]);//计量单位

		var formsid=$('#formid').combobox('getValue');
		$.get(depart, {"year": year,"indicatorType":indicatorType,"iname":iname,"page": curPage, "pageSize": pageSize,"formsid":formsid}, function (json) {

			var code=json.code;
	    	if(code!=200){
	    	  $('#tt').datagrid({data:[]});
	    	  return;
	    	}
			var data = json.data;
			var total = data.size;
			var totalPage = Math.ceil(total / pageSize);
			var start = (curPage - 1) * pageSize;
			var dataLength = 0;
			data = data["results"];
			if (data != null) {
				dataLength = data.length;
			}

			// 获取有哪些部门
			var showDepartName = [];
			//显示的具体数据集合
			var r = [];
			// 显示的对象，标题对应领域数值
			var e = {};
			for(var i=0; i< data.length; i++){
				//初始化对象
				r[i] = {};
				r[i]['iname'] = data[i]['iname'];
				r[i]['code'] = data[i]['code'];
				r[i]['unit'] = data[i]['unit'];

				for(var j=0;j<data[i]['list'].length;j++){
					e[data[i]['list'][j]['sname']] = data[i]['list'][j]['sname'];
					if (!showDepartName.includes(data[i]['list'][j]['sname'])) {
						showDepartName.push(data[i]['list'][j]['sname']);
					}
					// {
					// 	"sname": "枣庄统计",
					// 	"departid": 36,
					// 	"2010": "1_0.0_0.0_0_"
					// },
					for(var a in data[i]['list'][j]) {
						if (!isNaN(a) && !a.indexOf('_')!=-1) {
							r[i][data[i]['list'][j]['sname']] =data[i]['list'][j][a];
						}
					}
				}
			}

			for(var z in e){
				var c = {title:z, field:z, width:80,
					// 数据上报的类型_每年的目标值_数值_显示数据展示时效果的规则_每年的备注
					formatter: function (value, row, index) {
						if(value !=null && value.indexOf('_')!=-1){
							return value.split("_")[2];
						}else{
							return value;
						}
					}
				};
				reportShowColumns.push(c);
			}

			var iH = document.documentElement.clientHeight;
			var h;

			if(open==true&&isshow==true){
				h = iH-500;
			}else {
				h = iH-115;
			}

            $('#tt').datagrid( {
                width : '100%',
                height : h,
                frozen:true,
                columns : [
                       reportShowColumns
                     ],
                collapsible: true,
     	    	singleSelect : false,// 是否单选
     	    	checkOnSelect: true,//选中行后,checkbox选中
     	    	selectOnCheck: true,//选中行后,checkbox选中
     	    	rownumbers: true,
     			striped:true,//表格奇偶渐变色
     			pageNumber: curPage,//显示数据列用
     			pagination:true,//打开翻页功能
 		        pageSize: pageSize,
     		    pageList: [30, 50, 100, 500, 1000],
     		    data:r,
     		   onSelect:function(index,row) {
     	            //显示页面效果
     		    	reportcharts(row,true);
				   show.tableshow();
				   open = true;
     		   },
     	       onUnselect:function(index,row) {
    	            //取消
    		    	reportcharts(row,false);
    	        },
    	        onSelectAll:function(){
    	        	selectAll = true;
    	        },
    	        onUnselectAll:function(){
    	        	selectAll = false;
    	        }    
            });
            
		    var p = $('#tt').datagrid('getPager');
		    $(p).pagination({
			      total: total,
			      pageList: [30, 50, 100, 500, 1000],
			      pageSize: pageSize,
			      pageNumber: curPage,
			      beforePageText: '第',
			      afterPageText: '页    共 ' + totalPage + ' 页',
			      displayMsg: '当前显示 ' + (start + 1) + '-' + (start + dataLength) + ' 条记录 共 ' + total + ' 条记录',
			      onSelectPage: function (curPage, pageSize) {
			        query(curPage, pageSize,true);
			      },
			      onChangePageSize: function (ps) {
			        pageSize = ps;
			      }
		    });
		    
		    if(isTrue){
		    	reportcharts();	
		    }
		     //切换指标清空图形
		}, "json");
		
}
var dataData=[];
//画下方的表格图
function reportcharts(row,show){
	//画曲线图
    var categories = [];
    var series = [];    
    var departData = [];
    for(var i in row){
    	if(/^[\u4e00-\u9fa5]+$/.test(i)){  //正则判断是否为中文
    		if(i!="指标名称"&&i!="计量单位"){
    			categories.push(i);   //获取地市名称		
    		}
			if(row[i] !=null && row[i].indexOf('_')!=-1){
				row[i] = row[i].split("_")[2];
			}
			departData.push(row[i]); //获取指标值
    	} 	
    } 
    if(show==true){
    arr.push(row.iname);
    dataData.push({ 
    	 name: row.iname,
         type: 'bar',
         label: {
             normal: {
                 show: true,
                 position: 'top'
             }
         },
         data: departData
    	});   
    }
    else if(show==false){
    	 for(var i=0;i<dataData.length;i++){
			 if(dataData[i]['name']==row.iname){
				 dataData.splice(i,1);
			 }
	    	 for(var n=0; n<arr.length; n++){
	    		 if(arr[n]==row.iname){
	    			 arr.splice(n,1);
	    		 }
	    	 }
    	 }
    } 

    series.push({key:'value', name: '上报数值', data: departData, visible: true, color: SeriesColor.vvLinearRegression});  
  
    $("#chartpanel").panel({title: "数据趋势图"});
    $("#chart").width($("#chartpanel").width()-40);
	$("#chart").height("400px");
	var myChart = echarts.init(document.getElementById('chart'));
            // 指定图表的配置项和数据
            option = {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: arr
                },
                toolbox: {
                    show: true,
					orient:'vertical',
        			y:'center',
        			itemSize:24,
                    feature: {
                        mark: {show: true},
                        magicType: {show: true, type: ['line','bar','stack','tiled','pie','funnel']},
                        saveAsImage : {
                            show : true,
                            title : '保存为图片',
                            type : 'png',
                            lang : ['点击保存']
                        },
                        restore: {show: true}
                    }
                },
                calculable: true,
                xAxis: [
            			{
            				type: 'category',
            				boundaryGap : true,
            				data: categories
            			}
            		],
                yAxis: [
                    {
                        type: 'value'
                    }
                ],
                series :dataData,
                color:['#63cee0','#63e0a7','#d2e063','#cc99cc','#ffcccc','#1962ad','#b47e8e']
            };
            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
}

var show = {
    tableshow:function () {
        show.a = !show.a;
        if(show.a){
            $("#chartpanel").panel("expand",true);
        }
    },
    photoshow:function () {
        show.a = false;
    }
};

$(function () {
	  var isTrue = false;
	  query(curPage, pageSize,'stance',isTrue);
	  loadYear();
	$('#indicatorType').combobox({
		onSelect:function(){
			isTrue = true;
			flip = false;
			query(curPage, pageSize,true,isTrue);
		}
	});
});

function queryList () {
		query(curPage, pageSize,true,true)
}

function Save_Excel() {//导出Excel文件
	if(selectAll==true){}
	else{
		if(arr.length==0){
			$.messager.alert('系统提示','请先勾选需要导出的指标，如需要导出所有指标数据请全选指标!','info')
			return;
		}
	}
    
    var grid = $("#tt");
    var name='各单位数据分析';
    var colums_all=grid.datagrid("options").columns;      		     //获得表格的所有列不包括冻结列
    var columses=[];
    var columss=[];
    for (var i = 1; i < colums_all[0].length; i++) {
        columss.push(colums_all[0][i]);
    }
    columses[0]=columss;
    var getSelections = grid.datagrid("getSelections");     //获得表格选中行数据 getSelections
    var obj = $.ExportExcelDlg({
        HeadInfo: columses,    //表头栏
        RowInfo: getSelections,		   //数据航
        FooterInfo: grid.datagrid("getFooterRows"),
        RowStart: 2,		   //导出行位置
        ColumStart: 2,		   //导出列位置
        SheetName: name,
        MainTitle: { Displayname: name, Alignment: 'Center' },
        SaveName: name,
        Swf: 'ExportExcel.swf'
    });
    obj.ExportExcelDlg('open');
}
